package ms.maplestory.boot.service;

import ms.maplestory.boot.client.Account;
import ms.maplestory.boot.client.User;
import ms.maplestory.boot.repository.AccountRepository;
import lombok.RequiredArgsConstructor;
import ms.maplestory.boot.world.LoginServer;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Objects;

@Service
@RequiredArgsConstructor
public class AccountService extends JpaService<Account, Integer> {

    private final AccountRepository accountRepository;
    private final UserService userService;

    @Override
    public AccountRepository getRepository() {
        return this.accountRepository;
    }


    @Transactional
    public Account initAccountUserWorld(Account account, int worldId) {
        User user = userService.createUser(account, worldId);
        account.addUser(user);
        return accountRepository.save(account);
    }

    @Transactional
    public void unstuck(Account account) {
        if (Objects.isNull(account)) {
            return;
        }
        LoginServer.getInstance().removeAccount(account);
        save(account);
    }
}